import { useState, useRef } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components'
import type { ActionType } from '@ant-design/pro-components'
import { Button, Tag, Modal, message } from 'antd'
import { EditOutlined, DeleteOutlined, CheckCircleTwoTone, ExclamationCircleOutlined } from '@ant-design/icons'
import { GetListFnc, DeleteCateogryFnc } from '@/services/category'
import AddEdit from './components/AddEdit';

const Category = () => { 
  const actionRef: any = useRef<ActionType>()
  const [modal, contextHolder] = Modal.useModal()
  const [pageSize, setPageSize] = useState(2); // table 每页显示的条数
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1)
  const [isModalOpen, setIsModalOpen] = useState(false); // 添加修改分类的盒子
  const [openType, setOpenType] = useState(''); // 要么是add 要么是edit 打开盒子传值 关闭盒子不传值
  const [catID, setCatID] = useState('') // 编辑分类ID
  const [catName, setCatName] = useState('') // 编辑分类名称

  // 获得table数据
  const getData = async (params: any) => {
    const res = await GetListFnc({type: 3, pageNum: current, pageSize: params.pageSize })
    setTotal(res.data.length)
    return {
      data: res.data,
      success: res.meta.status === 200
    }
  }

  // 排序tag
  const levelTag = (level: number) => {
    if(level === 0) {
      return <Tag color='blue'>一级</Tag> 
    } else if(level === 1) {
      return <Tag color='green'>二级</Tag> 
    } else {
      return <Tag color='orange'>三级</Tag> 
    }
  }

  // 删除分类
  const deleteCategory = (id: number) => {
    modal.confirm({
      icon: <ExclamationCircleOutlined />,
      content: '此操作将永久删除分类, 是否继续?',
      onOk: async () => {
        const res = await DeleteCateogryFnc(id)
        if (res.meta.status === 200) {
          message.open({
            type: 'success',
            content: '删除成功',
            duration: 1.5,
            onClose: () => {
              if (total % pageSize === 1) {
                setCurrent(current - 1);
              }
              actionRef.current?.reload();
            },
          });
        }
      },
    });
  }

   // 打开添加 修改 分类盒子 给子组件使用
   const openBox = (flag: boolean, ...args: any[]) => {
    setIsModalOpen(flag)
    setOpenType(args[0])
    setCatName(args[1])
    setCatID(args[2])
  };

  const columns: any = [
    {title: '分类名称', dataIndex: 'cat_name', key: 'cat_name', width: 150},
    {title: '是否有效', dataIndex: 'cat_deleted', key: 'cat_deleted', width: 150, render: (flag: boolean) => {
      return flag === false ? <CheckCircleTwoTone twoToneColor='#339900' /> : <CheckCircleTwoTone twoToneColor='#FF0000' />
    }},
    {title: '排序', dataIndex: 'cat_level', key: 'cat_level', width: 100, render: (level: number) => levelTag(level)},
    {title: '操作', width: 220, render: (info: {cat_name: string, cat_id: number}) => {
      return (
        <>
          <Button type='primary' size='small' icon={<EditOutlined/>} onClick={() => openBox(true, 'edit', info.cat_name, info.cat_id)} style={{marginRight: '10px'}}>编辑</Button> 
          <Button type="primary" danger size='small' icon={<DeleteOutlined/>} onClick={() => deleteCategory(info.cat_id)}>删除</Button> 
        </>
      )
    }},
  ]

  return (
    <>
    {contextHolder}
    <PageContainer header={{ title: '', breadcrumb: { items: [{ title: '商品管理' }, { title: '商品分类' }] }}}>
      <ProTable
        columns={columns}
            actionRef={actionRef}
            rowKey={(record) => record.cat_id}
            request={(params) => getData(params)}
            scroll={{ x: 500 }}
            bordered
            search={false}
            headerTitle={<Button type="primary" onClick={() => openBox(true, 'add')}>添加分类</Button>}
            onChange={({ current }: any) => setCurrent(current)}
            pagination={{
                pageSize: pageSize,
                showSizeChanger: true,
                pageSizeOptions: [2, 5, 10],
                onShowSizeChange: (_, size) => setPageSize(size),
        }}
      />
    </PageContainer>

    {/* 添加修改分类盒子 */}
    <AddEdit openBox={openBox} openType={openType} isModalOpen={isModalOpen} actionRef={actionRef} catName={catName} catID={catID}/>
    </>
  )
}

export default Category